<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/3/15
  Time: 20:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>AjaxPost请求</title>
</head>
<body>
<%-- 当 输入框失去焦点 提交 post请求--%>
<form >
    用户名【GET】：<input type="text" id="usernameID" name="username" maxlength="4">
</form>
<hr>
<%--显示提示--%>
<span id="resId"></span>
<script type="text/javascript">
    //创建AJAX异步对象，即XMLHttpRequest
    function createAJAX(){
        var ajax = null;
        try{
            ajax = new ActiveXObject("microsoft.xmlhttp");
        }catch(e1){
            try{
                ajax = new XMLHttpRequest();
            }catch(e2){
                alert("你的浏览器不支持ajax，请更换浏览器");
            }
        }
        return ajax;
    }
</script>

<script type="text/javascript">
    document.getElementById("usernameID").onblur = function () {
        // 获取当前文本框的值
        var username = this.value;
        if(username.length==0){
            document.getElementById("resId").innerHTML = "请输入用户名"
        }else {
//            发送Ajax 请求
            var ajax = createAJAX();
     /*       username = encodeURI(username);
            var url = "${pageContext.request.contextPath}/post?username="+username;
            ajax.open("GET",url);
            ajax.send(null);
            ajax.onreadystatechange = function () {
                if(ajax.readyState==4){
                    if(ajax.status==200){
                        var tip = ajax.responseText;
                        document.getElementById("resId").innerHTML=tip;
                    }
                }
            }
            */

            var url = "${pageContext.request.contextPath}/post";
            ajax.open("POST",url);
            ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
            ajax.send("username="+username);
            ajax.onreadystatechange = function () {
                if(ajax.readyState==4){
                    if(ajax.status==200){
                        var tip = ajax.responseText;
                        document.getElementById("resId").innerHTML=tip;
                    }
                }
            }

        }

    }
</script>

</body>
</html>
